﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CanPower.Models
{
    public class Logger
    {
        public static Logger logger;

        private string dir = @"D:/Power/Log/";

        private string path = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".log";

        private readonly object _lock = new object();

        public ObservableCollection<string> Logs { get; set; } = new ObservableCollection<string>();
        public Logger(string path)
        {
            if (File.Exists(path)) 
                throw new Exception($"The file {path} already exists!");
            if (path != null) this.path = path;
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            File.Create(dir + this.path).Close();
            this.path = dir + this.path;
        }
        public static Logger GetInstance(string path = null)
        {
            if (logger == null) logger = new Logger(path);
            return logger;
        }
        public void WriteLog(string message)
        {
            SaveToTxt(message);
            WriteToUi(message);
        }
        public void WriteToUi(string message)
        {
            Logs.Add(message);
        }

        private void SaveToTxt(string message)
        {
            lock (_lock)
            {
                File.AppendAllText(path, message + "\n");
            }
        }
        public void Clear()
        {
            Logs.Clear();
        }
    }
}
